package com.jacky.flutter_screen_recording;

import static android.os.Process.myUid;
import android.content.pm.ServiceInfo;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

import com.jacky.log.Logger;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class AppUtils {

    private static String CHANNEL_ID = "ScreenRecordService";

    /**
     * 将当前应用从后台切换到前台界面
     *
     * @param context
     * @return true 当前进程已在顶部；false 当前进程在后台
     */
    @SuppressLint("MissingPermission")
    public static boolean moveToFont(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskList = manager.getRunningTasks(20);
        int i = 0;
        for (ActivityManager.RunningTaskInfo rti : taskList) {
            //找到当前应用的task，并启动task的栈顶activity，达到程序切换到前台
            String packName = rti.topActivity.getPackageName();
            String packName2 = context.getPackageName();
            if (packName.equals(packName2)) {
                for(int k=0;k<5;k++){ //多试几次
                    manager.moveTaskToFront(rti.id, ActivityManager.MOVE_TASK_NO_USER_ACTION);
                }
                if (i == 0) return true;
                return false;
            }
            i++;
        }
        return false;
    }

    public static boolean saveBitmap(File file, Bitmap bm, Bitmap.CompressFormat format, int quality) {
        if(bm == null || bm.isRecycled()) return false;

        OutputStream stream = null;
        try {
            stream = new FileOutputStream(file);
            bm.compress(format, quality, stream);
            stream.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            close(stream);
        }
    }

    public static void close(Closeable closeable) {
        if(closeable == null) return;
        try {
            closeable.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean canDrawOverlays(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        return Settings.canDrawOverlays(context);
    }

    /**
     * @param pattern
     * @return 要求的格式返回当前时间;
     */
    public static String formatTime(String pattern, long longTime) {
        SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.CHINA);
        Date curDate = new Date(longTime);
        return format.format(curDate);
    }

    /**
     * 创建 通知通道 并获取通知对象
     * @param title  通知标题
     * @param content 通知内容
     */
    public static Notification getNotification(Context context, CharSequence name,
                                               CharSequence title,CharSequence content) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            //创建 通知通道：channelId+标题+描述
            NotificationChannel notificationChannel = new NotificationChannel(
                    CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setShowBadge(true);
            notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            manager.createNotificationChannel(notificationChannel);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(content);
        return builder.build();
    }

    /**
     * 通知   如录屏的录制中
     */
    public static void startForegroundWithNotification(Service service, int notificationId, CharSequence title) {
        Notification builder = getNotification(service.getApplicationContext(),title,title, null);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            service.startForeground(notificationId, builder,
                    ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION|ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE);
        } else {
            service.startForeground(notificationId, builder);
        }
    }

    public static void cancelNotification(Context context,int id){
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(id);
    }

    /**
     * 获取网络连接的方式
     * @return
     */
    public static int getNetworkStatus(Context context) {
        ConnectivityManager manager =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo network = manager == null ? null : manager.getActiveNetworkInfo();
        if(network == null) return -1;
        return network.getType();
    }

    public static int getNetworkType(Context context){
        int type = getNetworkStatus(context);
        switch (type){
            case ConnectivityManager.TYPE_MOBILE:
            case ConnectivityManager.TYPE_MOBILE_DUN:
            case ConnectivityManager.TYPE_MOBILE_HIPRI:
            case ConnectivityManager.TYPE_MOBILE_MMS:
            case ConnectivityManager.TYPE_MOBILE_SUPL:
                return ConnectivityManager.TYPE_MOBILE;
            case ConnectivityManager.TYPE_WIFI:
                return ConnectivityManager.TYPE_WIFI;
        }
        return  -1;
    }

    public static int type() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            return WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
    }

    public static void showToast(Context context, CharSequence msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 去掉时间的毫秒数
     * @param time  带毫秒的时间
     * @return
     */
    public static long getTimeNoMillis(long time) {
        return (time) / 1000 * 1000;
    }

    /**
     *
     * @param root 根目录
     * @param deleteSelf 是否删除根目录
     */
    public static void deleteChildFiles(File root, boolean deleteSelf) {
        if(root == null || !root.exists()) return;
        File[] file = root.listFiles();
        if(file != null) {
            for (File f : file) {
                if (f.isDirectory()) {
                    deleteChildFiles(f, true);
                } else {
                    f.delete();
                }
            }
        }
        if(deleteSelf) {
            root.delete();
        }
    }
	
	 public static boolean startActivity(Context context,Intent intent) {
        try {
            if(intent == null) return false;
            context.startActivity(intent);
        } catch (Exception e) {
            Log.i("ScreenRecord","startActivity " + intent.getAction() + " error " + e.getMessage());
            return false;
        }
        return true;
    }

    /**null 代表Android sdk版本小于23，true代表已经是白名单了 */
    public static Boolean isIgnoreBatteryOptimizations(Context context){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            return powerManager.isIgnoringBatteryOptimizations(context.getPackageName());
        }
        return null;
    }

    /**请求 加入白名单  电量优化白名单*/
    public static Boolean requestIgnoreBatteryOptimizations(Context context){
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + context.getPackageName()));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            return startActivity(context,intent);
        }
        return null;
    }

    /**打开 自动启动管理
     * xiaoerbuyu1233 <a href="https://blog.csdn.net/xiaoerbuyu1233/article/details/122130165">后台运行白名单</a>
     * @param noWayToSetting 没有其他方法 则打开设置页面
     */
    public static Boolean toBootManagerActivity(Context context,boolean noWayToSetting){
        if(Build.BRAND == null) return null;
        String name = Build.BRAND.toLowerCase();
        Log.d("Logger","==========toBootManagerActivity name "+name+", BRAND "+Build.BRAND);
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PackageManager pm = context.getPackageManager();

        Boolean can = null;
        for (Intent aIntent : POWER_MANAGER_INTENTS) {
            if (pm.resolveActivity(aIntent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                aIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                can = startActivity(context, aIntent);
                String cls = aIntent.getComponent() == null ? null : aIntent.getComponent().getClassName();
                Log.d("Logger", "==========toBootManagerActivity intent class name " + cls + ", can " + can);
                break;
            }
        }
        if (can != null && can) return true;
        switch (name){
            case "huawei":
            case "honor":
                //华为手机管家的启动管理页: 应用启动管理 -> 关闭应用开关 -> 打开允许自启动
                //String pkg = "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity";
                ///pkg + ".optimize.bootstart.BootStartActivity";
                ///pkg + ".optimize.process.ProtectActivity";
                ///pkg + ".appcontrol.activity.StartupAppControlActivity";
                //Toast.makeText(context, "开启失败，请手动到设置-应用和服务-应用启动管理，设置为手动管理", Toast.LENGTH_SHORT).show();
                break;
            case "xiaomi":
                //小米 授权管理 -> 自启动管理 -> 允许应用自启动
                intent.setComponent(new ComponentName("com.miui.securitycenter","com.miui.permcenter.autostart.AutoStartManagementActivity"));
                can = startActivity(context,intent);
                break;
            case "oppo":
                //权限隐私 -> 自启动管理 -> 允许应用自启动
                can = startActivity(context,pm.getLaunchIntentForPackage("com.coloros.phonemanager"));
                if(!can){
                    can = startActivity(context,pm.getLaunchIntentForPackage("com.oppo.safe"));
                }
                if(!can){
                    can = startActivity(context,pm.getLaunchIntentForPackage("com.coloros.oppoguardelf"));
                }
                if(!can){
                    can = startActivity(context,pm.getLaunchIntentForPackage("com.coloros.safecenter"));
                }
                break;
            case "vivo":
                //权限管理 -> 自启动 -> 允许应用自启动
                can = startActivity(context, pm.getLaunchIntentForPackage("com.iqoo.secure"));
                break;
            case "meizu":
                //权限管理 -> 后台管理 -> 点击应用 -> 允许后台运行
                can = startActivity(context,pm.getLaunchIntentForPackage("com.meizu.safe"));
                break;
            case "samsung":
                //自动运行应用程序 -> 打开应用开关 -> 电池管理 -> 未监视的应用程序 -> 添加应用
                can = startActivity(context,pm.getLaunchIntentForPackage("com.samsung.android.sm_cn"));
                if(!can){
                    can = startActivity(context,pm.getLaunchIntentForPackage("com.samsung.android.sm"));
                }
                break;
            case "letv":
                //乐视  自启动管理 -> 允许应用自启动
                intent.setComponent(new ComponentName("com.letv.android.letvsafe","com.letv.android.letvsafe.AutobootManageActivity"));
                can = startActivity(context,intent);
                break;
            case "smartisan":
                //锤子
                can = startActivity(context, pm.getLaunchIntentForPackage("com.smartisanos.security"));
                break;
            default:break;
        }
        if(!Boolean.TRUE.equals(can) && noWayToSetting){
            toSettings(context);
        }
        return can;
    }

    /**系统设置界面*/
    public static boolean toSettings(Context context){
        return startActivity(context,new Intent(Settings.ACTION_SETTINGS));
    }

    /**电量优化intent*/
    private static final Intent[] POWER_MANAGER_INTENTS = {
            new Intent().setComponent(new ComponentName("com.miui.securitycenter","com.miui.permcenter.autostart.AutoStartManagementActivity")),
            new Intent().setComponent(new ComponentName("com.letv.android.letvsafe","com.letv.android.letvsafe.AutobootManageActivity")),
            new Intent().setComponent(new ComponentName("com.huawei.systemmanager","com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity")),
            new Intent().setComponent(new ComponentName("com.huawei.systemmanager","com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity")),
            new Intent().setComponent(new ComponentName("com.huawei.systemmanager","com.huawei.systemmanager.optimize.process.ProtectActivity")),
            new Intent().setComponent(new ComponentName("com.huawei.systemmanager","com.huawei.systemmanager.optimize.bootstart.BootStartActivity")),
            new Intent().setComponent(new ComponentName("com.coloros.safecenter","com.coloros.safecenter.permission.startup.StartupAppListActivity")),
            new Intent().setComponent(new ComponentName("com.coloros.safecenter","com.coloros.safecenter.startupapp.StartupAppListActivity")),
            new Intent().setComponent(new ComponentName("com.oppo.safe","com.oppo.safe.permission.startup.StartupAppListActivity")),
            new Intent().setComponent(new ComponentName("com.iqoo.secure","com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity")),
            new Intent().setComponent(new ComponentName("com.iqoo.secure","com.iqoo.secure.ui.phoneoptimize.BgStartUpManager")),
            new Intent().setComponent(new ComponentName("com.vivo.permissionmanager","com.vivo.permissionmanager.activity.BgStartUpManagerActivity")),
            new Intent().setComponent(new ComponentName("com.samsung.android.lool","com.samsung.android.sm.ui.battery.BatteryActivity")),
            new Intent().setComponent(new ComponentName("com.samsung.android.tool","com.samsung.android.sm.ui.battery.BatteryActivity")),
            new Intent().setComponent(new ComponentName("com.htc.pitroad","com.htc.pitroad.landingpage.activity.LandingPageActivity")),
            new Intent().setComponent(new ComponentName("com.asus.mobilemanager","com.asus.mobilemanager.MainActivity")),
            new Intent().setComponent(new ComponentName("com.transsion.phonemanager","com.itel.autobootmanager.activity.AutoBootMgrActivity")),
    };

    /**获取应用列表权限*/
    public static boolean hasPackagesPermission(Context context) {
        Logger.d("===========SDK_INT ",Build.VERSION.SDK_INT);
        //Android 13及以上才判断
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
            AppOpsManager opsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            int mode = opsManager.unsafeCheckOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, myUid(), context.getPackageName());
            return AppOpsManager.MODE_ALLOWED == mode;
        }
        return true;
    }

    /**请求权限：获取应用列表权限*/
    public static boolean requestPackagesPermission(Context context){
        return  startActivity(context,new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
    }

    public static <T extends BroadcastReceiver> T unregisterReceiver(Context context, T receiver) {
        if(receiver == null || context == null) return null;
        try {
            context.unregisterReceiver(receiver);
        }catch (Exception ignored){}
        return null;
    }

    /**
     * dp转换成px
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static <T> T[] remove(T[] data, int index) {
        if(data == null || data.length <= index) return Arrays.copyOf(data, 0);

        T[] elementData = Arrays.copyOf(data, data.length - 1);
        System.arraycopy(data, index+1, elementData, index, data.length - index - 1);
        return elementData;
    }
}
